package com.xy.smartsms.db.carrierparam.entity;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.xy.smartsms.db.base.MixCursor;
import com.xy.smartsms.db.carrierparam.CarrierDBManager;
import com.xy.smartsms.util.Log;

import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by kangwenbo on 2017/3/28.
 */

public class WhiteListDb {
    //----- 建表 Start------ //
    public static final String KEY_ID = "_id";
    public static final String KEY_PHONE = "phone";
    public static final String KEY_NAME = "name";
    public static final String KEY_LEVEL = "level";
    public static final String KEY_MIN_LEN = "min_len";
    public static final String KEY_MAX_LEN = "max_len";
    public static final String KEY_LEN = "len";
    public static final String KEY_IS_SECTION_NO = "is_match_number";
    public static final String KEY_EXTENDVAL = "extendVal";

    public static final String NAME = "tb_white_list";

    public static final String DROP_TABLE = " DROP TABLE IF EXISTS " + NAME;
    public static final String CREATE_TABLE = "create table  if not exists "
            + NAME +
            " ("
            + KEY_ID + " INTEGER PRIMARY KEY,"
            + KEY_PHONE + " VARCHAR,"
            + KEY_NAME + " TEXT,"
            + KEY_EXTENDVAL + " TEXT,"
            + KEY_MIN_LEN + " INTEGER,"
            + KEY_MAX_LEN + " INTEGER,"
            + KEY_LEN + " INTEGER,"
            + KEY_IS_SECTION_NO + " INTEGER,"
            + KEY_LEVEL + " INTEGER"
            + ")";

    //----- 建表 end------ //

    private final String TAG = "OnlineConfigDb";

    private static WhiteListDb sWhiteListDb = null;
    private Context mContext;

    public WhiteListDb (Context context) {
        mContext = context;
    }

    public static WhiteListDb getInstance() {
    return sWhiteListDb;
    }
    public static WhiteListDb getInstance(Context context) {
        synchronized (WhiteListDb.class) {
            if (sWhiteListDb == null) {
                sWhiteListDb = new WhiteListDb(context);
            }
        }
        return sWhiteListDb;
    }

    public WhiteListItem queryByPhone(final String phone) {
        Log.d(TAG, "queryByPhone " + phone);
        WhiteListItem item = null;
        MixCursor cursor = null;
        try {
            cursor = CarrierDBManager.query(mContext, NAME, null, KEY_PHONE + "=?",
                    new String[]{phone});
            if (cursor != null && cursor.moveToFirst()) {
                item = cursorToWhiteListItem(cursor);
            }
        } catch (Throwable t) {
            Log.e(TAG, "queryByPhone", t);
        } finally {
            MixCursor.closeCursor(cursor, true);
        }
        return item;
    }

    private WhiteListItem cursorToWhiteListItem(MixCursor cursor) {
        WhiteListItem item = new WhiteListItem();
        item.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
        item.setNumber(cursor.getString(cursor.getColumnIndex(KEY_PHONE)));
        item.setLevel(cursor.getInt(cursor.getColumnIndex(KEY_LEVEL)));
        return item;
    }

    public void updateOrInsert(WhiteListItem item) {
        try {
            int num = CarrierDBManager.update(mContext, NAME, item.getContentValues(), KEY_PHONE
                    + "=?", new String[]{item.getNumber()});
            if (num <= 0) {
                CarrierDBManager.insert(mContext, NAME, item.getContentValues());
            }
        } catch (Throwable t) {
            Log.e(TAG, "initData ", t);
        }
    }

    public void delete(WhiteListItem item) {
        try {
            CarrierDBManager.delete(mContext, NAME, KEY_PHONE + "=?",
                    new String[]{item.getNumber()});
        } catch (Throwable t) {
            Log.e(TAG, "delete ", t);
        }
    }

    public List<WhiteListItem> getAllSpecialPhone() {
        List<WhiteListItem> mSpecialPhoneMap = new ArrayList<>();
        MixCursor cursor = null;
        try {
            cursor = CarrierDBManager.query(mContext, NAME, null, KEY_IS_SECTION_NO + " =?",
                    new String[]{String.valueOf(WhiteListItem.YES)});
            if (cursor != null) {
                int number = cursor.getColumnIndex(KEY_PHONE);
                int name = cursor.getColumnIndex(KEY_NAME);
                int level = cursor.getColumnIndex(KEY_LEVEL);
                int extendVal = cursor.getColumnIndex(KEY_EXTENDVAL);
                int maxLen = cursor.getColumnIndex(KEY_MAX_LEN);
                int minLen = cursor.getColumnIndex(KEY_MIN_LEN);
                int len = cursor.getColumnIndex(KEY_LEN);
                int isSectionNo = cursor.getColumnIndex(KEY_IS_SECTION_NO);
                while (cursor.moveToNext()) {
                    WhiteListItem item = new WhiteListItem();
                    item.setNumber(cursor.getString(number).replace("*", ""));
                    item.setName(cursor.getString(name));
                    item.setLevel(cursor.getInt(level));
                    item.setExtendVal(cursor.getString(extendVal));
                    item.setMaxLen(cursor.getInt(maxLen));
                    item.setMinLen(cursor.getInt(minLen));
                    item.setLen(cursor.getInt(len));
                    item.setIsSectionNo(cursor.getInt(isSectionNo));
                    mSpecialPhoneMap.add(item);
                }
            }

        } catch (Throwable t) {
            Log.e(TAG, "getAllSpecialPhone", t);
        } finally {
            MixCursor.closeCursor(cursor, true);
        }
        return mSpecialPhoneMap;
    }

    public List<WhiteListItem> initDataToDB(BufferedReader bufferedReader) {
        Log.v(TAG, "start insertDataToDB");
        List<WhiteListItem> specialPhoneMap = new ArrayList<>();
        SQLiteDatabase db = null;
        try {
            db = CarrierDBManager.getSQLiteDatabase(mContext);
            if (db == null)
                return specialPhoneMap;

            android.database.sqlite.SQLiteStatement insert = db.compileStatement("INSERT INTO " + NAME
                    + "(" + KEY_PHONE + "," + KEY_NAME + "," + KEY_LEVEL
                    + "," + KEY_IS_SECTION_NO + ")VALUES(?,?,?,?)");

            android.database.sqlite.SQLiteStatement insertSpecial = db.compileStatement("INSERT INTO "
                    + NAME + "(" + KEY_PHONE + "," + KEY_NAME + ","
                    + KEY_MAX_LEN + "," + KEY_MIN_LEN + "," + KEY_LEN
                    + "," + KEY_IS_SECTION_NO + "," + KEY_LEVEL
                    + ")VALUES(?,?,?,?,?,?,?)");

            android.database.sqlite.SQLiteStatement sqliteDelte = db.compileStatement("DELETE FROM "
                    + NAME);

            db.beginTransaction();
            String str;

            sqliteDelte.executeUpdateDelete();

            while ((str = bufferedReader.readLine()) != null) {
                String info[] = str.split(",");
                if (info == null || info.length < 4)
                    continue;
                String level = info[3];
                info[0] = info[0].trim();
                if (info[0].endsWith("*") && info.length > 6) {
                    insertSpecial.bindString(1, info[0]);
                    insertSpecial.bindString(2, info[1]);
                    insertSpecial.bindString(3, info[4]);
                    insertSpecial.bindString(4, info[5]);
                    insertSpecial.bindString(5, info[6]);
                    insertSpecial.bindString(6, String.valueOf(WhiteListItem.YES));
                    insertSpecial.bindString(7, level);
                    insertSpecial.executeInsert();

                    WhiteListItem item = new WhiteListItem();
                    item.setNumber(info[0]);
                    item.setName(info[1]);
                    item.setLevel(Integer.valueOf(level));
                    item.setMaxLen(Integer.valueOf(info[4]));
                    item.setMinLen(Integer.valueOf(info[5]));
                    item.setLen(Integer.valueOf(info[6]));
                    item.setIsSectionNo(WhiteListItem.YES);
                    specialPhoneMap.add(item);

                } else {
                    insert.bindString(1, info[0]);
                    insert.bindString(2, info[1]);
                    insert.bindString(3, level);
                    insert.bindString(4, String.valueOf(WhiteListItem.NO));
                    insert.executeInsert();
                }
            }

            Log.e(TAG, "end Init WhiteList");
        } catch (Throwable t) {
            Log.e(TAG, "insertDataToDB", t);
        } finally {
            if (db != null && db.inTransaction()) {
                db.setTransactionSuccessful();
                db.endTransaction();
            }
            CarrierDBManager.close(db);
        }
        return specialPhoneMap;
    }
}
